package de.earthquake;

import java.text.ParseException;

import model.Earthquake;
import model.EarthquakeEntry;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.google.gson.Gson;

import de.earthquake.parser.EarthquakeParser;

public class EarthquakeList extends ListFragment {
	private static final String TAG = EarthquakeList.class.getCanonicalName();
	private EarthquakeDetail fragment;
	private Earthquake parseXmlFile;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		EarthquakeParser parser = new EarthquakeParser();
		try {
			parseXmlFile = parser.parseXmlFile(CONSTANTS.PATH_TO_XML_FILE);
			EarthquakeArrayAdapter adapter = new EarthquakeArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, parseXmlFile.getEarthquakeEntries());
			setListAdapter(adapter);
			
			fragment = (EarthquakeDetail) getFragmentManager().findFragmentById(R.id.fragment_detail);
			
			if (fragment != null && fragment.isInLayout()) {
				getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
				Bundle extras = getActivity().getIntent().getExtras();
			}
		} catch (ParseException e) {
			Log.e(TAG, e.getLocalizedMessage(), e);
		}
		
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		showDetails(position);
	}
	
	void showDetails(int position) {
		EarthquakeEntry item = (EarthquakeEntry) getListAdapter().getItem(position);
		if (fragment != null && fragment.isInLayout()) {
            fragment.setText(item);
			
		} else {
			Intent intent = new Intent(getActivity(), FragmentDetailActivity.class);
			Gson gson = new Gson();
			intent.putExtra(CONSTANTS.EARTHQUAKE_JSON, gson.toJson(item));
			startActivity(intent);

		}
	}
}